package cc.idoone.joddhttp.demo;

import jodd.http.HttpProgressListener;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;

import java.io.File;
import java.util.HashMap;

/**
 * @author hemj
 * @version 2017/7/31
 */
public class PostRequestDemo {
    private static final String URL = "http://localhost:8088/joddhttp/test";

    public static void main(String[] args) {
        HttpRequest httpRequest = HttpRequest.post(URL);
        HttpResponse response = httpRequest.send();
        System.out.println(response);
        System.out.println(response.charset("UTF-8").bodyText());

        // 或者一步步构建
        HttpRequest request = new HttpRequest();
        request
                .method("POST")
                .protocol("http")
                .host("localhost")
                .port(8088)
                .path("/joddhttp/test");
        System.out.println(request.send().charset("UTF-8").bodyText());

        // 带查询参数
        System.out.println(HttpRequest.post(URL + "?uid=1")
                .send().charset("UTF-8").bodyText());

        // 带查询参数
        HashMap<String, Object> formMap = new HashMap<>();
        formMap.put("form", "formValue");
        System.out.println(HttpRequest.post(URL + "?uid=1")
                .acceptEncoding("gzip")
                .header("header-1", "header-1")
                .header("TOKEN", "123")
                .query("uname", "hemj")
                .form("formField1", "1")
                .form(formMap)
                .send().charset("UTF-8").bodyText());

        // 上传文件
        httpRequest = HttpRequest
                .post(URL + "?uid=1")
                .query("uname", "hemj")
                .form(
                        "mimeType", "application/zip",
                        "title", "test.zip",
                        "file", new File("E:\\git.oschina\\my_log\\hst.txt")
                ).monitor(new HttpProgressListener() {
                    @Override
                    public void transferred(int i) {
                        System.out.println(i + "/" + size);
                    }
                });
        System.out.println(httpRequest.send().charset("UTF-8").bodyText());
    }
}
